<?php
namespace addons\TfFutures\backend\controllers;

use addons\TfFutures\common\models\Lever;
use addons\TfFutures\common\models\MemberLever;
use common\helpers\ArrayHelper;
use Yii;
use yii\data\Pagination;


class MemberLeverController extends BaseController
{
    public $modelClass = MemberLever::class;
    /**
     * 首页
     *
     * @return string
     */
    public function actionIndex()
    {
        $search = Yii::$app->request->get('keyword','');
        $types   = Yii::$app->request->get('type');

        $data   = $this->modelClass::find()->joinWith('member');
        if (!empty($search)) {
            $data->andFilterWhere(['or',['like','rf_member.username',$search],['like','rf_member.mobile',$search]]);
        }
        if (!empty($types)) {
            $data->andFilterWhere([$this->modelClass::tableName().'.lever_id'=>$types]);
        }
        $pages  = new Pagination(['totalCount' => $data->count(), 'pageSize' => $this->pageSize]);
        $models = $data->offset($pages->offset)->orderBy('id desc')->limit($pages->limit)->all();

        //获取杠杆分类
        $type = Lever::find()->select('id,name')->where(['status'=>'1'])->all();
        $typeArray = ArrayHelper::map($type,'id','name');
        return $this->render($this->action->id, [
            'models' => $models,
            'pages' => $pages,
            'typeArray' => $typeArray,
            'type' => $types,
            'keyword'=> $search,
        ]);
    }

    /**
     * 删除
     *
     * @param $id
     * @return mixed
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        if ($this->modelClass::findOne($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }

        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }

    /*
     * 审核
     * */
    public function actionStatus($id,$status){
        $model = $this->modelClass::findOne($id);
        if (empty($model)) {
            $this->message(200, '未查询到该申请', 'error');
        }
        $model->state = $status;
        return $model->save()
            ? $this->message('成功', $this->redirect(['index']), 'success')
            : $this->message($this->getError($model), $this->redirect(['index']), 'error');
    }
}